/*
 * 文件名：IPFormatHandler.java
 * 版权：亚信科技(南京)版权所有
 * 描述：TODO
 * 修改人：napo
 * 修改时间：2015-12-15
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;

import com.ailk.bigdata.etl.realstream.server.service.FormatHandler;

/**
 * @description TODO
 * @author [xuwei3]
 * @version [版本号,2015-12-15]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class IPFormatHandler extends FormatHandler
{

	/**
	 * @see com.ailk.bigdata.etl.realstream.server.service.FormatHandler#handleRequest(io.netty.buffer.ByteBuf,
	 *      java.lang.StringBuilder)
	 */
	@Override
	public void handleRequest(ByteBuf byteBuf, StringBuilder content)
	{

		String value = "";

		if (ipVer == 4)
		{
			byteBuf.readBytes(12);

			value = binary2Ipv4Address(byteBuf);
		}
		else if (ipVer == 6)
		{
			value = binary2Ipv6Address(byteBuf);
		}

		content.append(value);

		if (getSuccessor() != null)
		{
			content.append(separator);
			getSuccessor().handleRequest(byteBuf, content);
		}

		value = null;

	}

	private String binary2Ipv4Address(ByteBuf byteBuf)
	{
		String ip = "";
		for (int i = 0; i < 4; i++)
		{
			ip += byteBuf.readUnsignedByte() + ".";
		}
		return ip.substring(0, ip.length() - 1);
	}

	private String binary2Ipv6Address(ByteBuf byteBuf)
	{
		byte[] cbite = byteBuf.readBytes(16).array();
		String hexString = toHexString(cbite);
		if (hexString.matches("^[Ff]+$"))
		{
			return "";
		}
		else
		{
			String ip = "";
			for (int i = 0; i < 16; i++)
			{
				ip += toHex(cbite[i]);
				if ((i + 1) % 2 == 0)
				{
					ip += ":";
				}
			}
			return ip.substring(0, ip.length() - 1);
		}

	}

}
